package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

// 业务层, 处理User相关的业务
public class UserService {
    // 登录功能
    public User login(String username, String password) {
        // 调用dao的select查询用户
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.select(username, password);
        sqlSession.close();

        return user;
    }

    // 注册功能
    public boolean register(User user) {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 调用dao的通过用户名查询用户
        User u = mapper.selectByUsername(user.getUsername());

        if (u == null) {
            // 如果没有这个用户,调用dao添加用户,完成注册
            mapper.add(user);
            sqlSession.commit();
        }

        sqlSession.close();
        return u == null;
    }
}
